package com.mbw.service;

import cn.hutool.core.text.CharSequenceUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.RandomUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.mbw.mapper.OAuth2ClientMapper;
import com.mbw.pojo.OAuth2Client;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;


@Service
public class OAuth2ClientService extends ServiceImpl<OAuth2ClientMapper, OAuth2Client> {
	@Autowired
	private OAuth2ClientMapper oAuth2ClientMapper;
	@Autowired
	private PasswordEncoder passwordEncoder;

	public OAuth2Client queryClientByClientId(String clientId){
		return oAuth2ClientMapper.queryByClientId(clientId);
	}

	public String getClientIdUnique(OAuth2Client oAuth2Client){
		Long id = ObjectUtil.isEmpty(oAuth2Client.getId()) ? -1: oAuth2Client.getId();
		String clientId = RandomUtil.randomString(16);
		OAuth2Client oAuthClient = oAuth2ClientMapper.queryClientUnique(clientId);
		if(ObjectUtil.isNotEmpty(oAuthClient) && !oAuthClient.getId().equals(id)){
			//说明有重复，重新生成一次
			return getClientIdUnique(oAuth2Client);
		}else {
			return clientId;
		}
	}

	public OAuth2Client createOAuth2Client(OAuth2Client oAuth2Client){
		String clientId = oAuth2Client.getClientId();
		if(CharSequenceUtil.isBlank(clientId)){
			clientId = getClientIdUnique(oAuth2Client);
		}
		String clientSecret = oAuth2Client.getClientSecret();
		if(CharSequenceUtil.isBlank(clientSecret)) {
			clientSecret = RandomUtil.randomString(16);
		}
		String clientSecretEncoded = passwordEncoder.encode(clientSecret);
		oAuth2Client.setClientId(clientId);
		oAuth2Client.setClientSecret(clientSecretEncoded);
		oAuth2ClientMapper.insert(oAuth2Client);
		oAuth2Client.setClientSecret(clientSecret);
		return oAuth2Client;
	}
}
